<template>
  <div class="koi-flex">
    <KoiCard>
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true">
        <el-form-item label="知识库名称" prop="libraryName">
          <el-input
            placeholder="请输入知识库名称"
            v-model="searchParams.libraryName"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          ></el-input>
        </el-form-item>
        <el-form-item label="知识库状态" prop="libraryStatus">
          <el-select
            placeholder="请选择知识库状态"
            v-model="searchParams.libraryStatus"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          >
            <el-option
              v-for="koi in koiDicts.sys_switch_status"
              :key="koi.dictValue"
              :label="koi.dictLabel"
              :value="koi.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain @click="handleSearch" v-auth="['blog:library:search']">{{
            $t("button.search")
          }}</el-button>
          <el-button type="danger" icon="refresh" plain @click="resetSearch">{{ $t("button.reset") }}</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['blog:library:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">{{ $t("button.add") }}</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['blog:library:update']">
          <el-button type="success" icon="edit" plain @click="handleUpdate()" :disabled="single">{{
            $t("button.update")
          }}</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['blog:library:delete']">
          <el-button type="danger" icon="delete" plain @click="handleBatchDelete()" :disabled="multiple">{{
            $t("button.delete")
          }}</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
      </el-row>

      <div class="h-20px"></div>
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        border
        :data="tableList"
        :empty-text="$t('msg.null')"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column :label="$t('table.number')" prop="libraryId" width="80px" align="center" type="index"></el-table-column>
        <el-table-column
          label="知识库名称"
          prop="libraryName"
          width="280px"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="图片" prop="picture" width="120px" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            <div class="flex flex-justify-center">
              <el-image
                class="max-w-100% h-52px rounded-8px"
                :src="scope.row.picture"
                fit="contain"
                :preview-teleported="true"
                :preview-src-list="[scope.row.picture]"
              >
                <!-- 这个地方若加载不出来，暂时用一个默认图片代替 -->
                <!-- https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png -->
                <template #error>
                  <el-image
                    src="https://i.postimg.cc/zBRKsrdv/carousel66.jpg"
                    fit="cover"
                    :preview-teleported="true"
                    :preview-src-list="['https://i.postimg.cc/zBRKsrdv/carousel66.jpg']"
                    class="max-w-100% h-52px rounded-8px"
                  ></el-image>
                </template>
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="知识库状态" prop="libraryStatus" width="100px" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.libraryStatus"
              :active-text="$t('dict.sys_switch_status.open')"
              :inactive-text="$t('dict.sys_switch_status.stop')"
              active-value="0"
              inactive-value="1"
              :inline-prompt="true"
              @change="handleSwitch(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sorted" width="80px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="备注" prop="remark" width="280px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180px" align="center"></el-table-column>
        <el-table-column
          :label="$t('table.operate')"
          align="center"
          width="190"
          fixed="right"
          v-auth="['blog:library:update', 'blog:library:delete']"
        >
          <template #default="{ row }">
            <el-tooltip :content="$t('button.preview')" placement="top">
              <el-button
                type="info"
                icon="View"
                circle
                plain
                @click="handlePreview(row)"
                v-auth="['blog:library:preview']"
              ></el-button>
            </el-tooltip>
            <el-tooltip :content="$t('button.update')" placement="top">
              <el-button
                type="primary"
                icon="Edit"
                circle
                plain
                @click="handleUpdate(row)"
                v-auth="['blog:library:update']"
              ></el-button>
            </el-tooltip>
            <el-tooltip :content="$t('button.delete')" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="handleDelete(row)"
                v-auth="['blog:library:delete']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="编辑目录" placement="top">
              <el-button
                type="warning"
                icon="FolderOpened"
                circle
                plain
                @click="handleCatalog(row)"
                v-auth="['blog:library:catalog']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div class="h-20px"></div>
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        v-show="total > 0"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <!-- 添加 OR 修改 -->
      <KoiDrawer
        ref="koiDrawerRef"
        :title="title"
        @koiConfirm="handleConfirm"
        @koiCancel="handleCancel"
        :loading="confirmLoading"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="auto" status-icon>
            <el-row>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="知识库名称" prop="libraryName">
                  <el-input v-model="form.libraryName" placeholder="请输入知识库名称" maxlength="256" show-word-limit clearable />
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="图片" prop="picture">
                  <!-- 方形示例 -->
                  <KoiUploadImage v-model:imageUrl="form.picture" width="214px">
                    <template #content>
                      <el-icon><Picture /></el-icon>
                      <span>请上传图片</span>
                    </template>
                    <template #tip>图片最大为 3M</template>
                  </KoiUploadImage>
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="图片地址" prop="picture">
                  <el-input type="textarea" v-model="form.picture" :rows="6" placeholder="请输入图片地址" clearable />
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="知识库状态" prop="libraryStatus">
                  <el-select placeholder="请选择知识库状态" v-model="form.libraryStatus" clearable>
                    <el-option
                      v-for="koi in koiDicts.sys_switch_status"
                      :key="koi.dictValue"
                      :label="koi.dictLabel"
                      :value="koi.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="排序" prop="sorted">
                  <el-input-number v-model="form.sorted" placeholder="请输入数字" :min="1" clearable />
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    type="textarea"
                    v-model="form.remark"
                    :rows="5"
                    placeholder="请输入备注"
                    maxlength="64"
                    show-word-limit
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </KoiDrawer>
    </KoiCard>
  </div>
</template>

<script setup lang="ts" name="libraryPage">
import { nextTick, ref, reactive, onMounted } from "vue";
import { koiMsgSuccess, koiMsgError, koiMsgWarning } from "@/utils/koi.ts";
import { ElMessageBox } from "element-plus";
import { listPage, getById, add, update, deleteById, batchDelete, updateStatus, getSorted } from "@/api/blog/library/index.ts";
import { useI18n } from "vue-i18n";
import { useKoiDict } from "@/hooks/dicts/index.ts";
import { useRouter } from "vue-router";

const router = useRouter();

const { koiDicts } = useKoiDict(["sys_switch_status"]);
const { t } = useI18n();
// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 表格数据
const tableList = ref<any>([]);

// 查询参数
const searchParams = ref({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  libraryName: undefined,
  libraryStatus: undefined
});

const total = ref<number>(0);

/** 重置搜索参数 */
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    libraryName: undefined,
    libraryStatus: undefined
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNo = 1;
  handleTableData();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

/** 数据表格 */
const handleListPage = async () => {
  try {
    tableList.value = []; // 重置表格数据
    loading.value = true;
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 数据表格[不带Loading，删除、批量删除等使用] */
const handleTableData = async () => {
  try {
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

// 获取表格数据
onMounted(() => {
  handleListPage();
});

const ids = ref([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.libraryId);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

/** 获取最新排序数字 */
const handleSorted = async () => {
  try {
    const res: any = await getSorted();
    form.value.sorted = res.data;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 添加 */
const handleAdd = () => {
  // 打开抽屉
  koiDrawerRef.value.koiOpen();
  // 重置表单
  resetForm();
  // 标题
  title.value = t("button.add");
  form.value.libraryStatus = "0";
  handleSorted();
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  try {
    const res: any = await getById(id);
    form.value = res.data;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 打开抽屉
  koiDrawerRef.value.koiOpen();
  // 重置表单
  resetForm();
  // 标题
  title.value = t("button.update");
  const id = row ? row.libraryId : ids.value[0];
  // 回显数据
  handleEcho(id);
};

// 添加 OR 修改抽屉Ref
const koiDrawerRef = ref();
// 标题
const title = ref();
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  libraryName: undefined,
  picture: undefined,
  libraryStatus: undefined,
  sorted: 1,
  remark: undefined
});

/** 清空表单数据 */
const resetForm = () => {
  // 等待 DOM 更新完成
  nextTick(() => {
    if (formRef.value) {
      // 重置该表单项，将其值重置为初始值，并移除校验结果
      formRef.value.resetFields();
    }
  });
  form.value = {
    libraryName: undefined,
    picture: undefined,
    libraryStatus: undefined,
    sorted: 1,
    remark: undefined
  };
};

/** 表单规则 */
const rules = reactive({
  libraryName: [{ required: true, message: "请输入知识库名称", trigger: "blur" }],
  picture: [{ required: true, message: "请输入图片", trigger: "blur" }],
  libraryStatus: [{ required: true, message: "请输入知识库状态", trigger: "blur" }],
  sorted: [{ required: true, message: "请输入排序", trigger: "blur" }]
});

// 确定按钮是否显示Loading
const confirmLoading = ref(false);

/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      if (form.value.libraryId != null && form.value.libraryId != "") {
        try {
          await update(form.value);
          koiMsgSuccess(t("msg.success"));
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiMsgError(t("msg.fail"));
        }
      } else {
        try {
          await add(form.value);
          koiMsgSuccess(t("msg.success"));
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiMsgError(t("msg.fail"));
        }
      }
    } else {
      koiMsgError(t("msg.validFail"));
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDrawerRef.value.koiClose();
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.libraryId;
  if (id == null || id == "") {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmDelete"), t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteById(id);
        handleTableData();
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 批量删除 */
const handleBatchDelete = () => {
  if (ids.value.length == 0) {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmDelete"), t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await batchDelete(ids.value);
        handleTableData();
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 状态开关 */
const handleSwitch = (row: any) => {
  let text = row.libraryStatus === "0" ? t("dict.sys_switch_status.open") : t("dict.sys_switch_status.stop");
  if (!row.libraryId || !row.libraryStatus) {
    row.libraryStatus = row.libraryStatus == "0" ? "1" : "0";
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmWant") + "[" + text + "]-[" + row.libraryName + "]?", t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await updateStatus(row.libraryId, row.libraryStatus);
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        row.libraryStatus = row.libraryStatus == "0" ? "1" : "0";
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      row.noticeStatus = row.noticeStatus == "0" ? "1" : "0";
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 编辑目录 */
const handleCatalog = (row: any) => {
  if (!row.libraryId) {
    koiMsgError(t("msg.fail"));
    return;
  }
  router.push("/blog/catalog/" + row.libraryId);
};

/** 预览 */
const handlePreview = (row: any) => {
  if (!row?.libraryId) {
    koiMsgError(t("msg.fail"));
    return;
  }
  router.push("/blog/library/preview/" + row.libraryId);
};
</script>

<style lang="scss" scoped></style>
